const { build } = require('node-xlsx');
const fs = require("fs");
const { resolve } = require('path')

let result = [['系统位置', '词条(中文)', '词条(英文)', '词条法文', '翻译问题']];

function getKeyValue(
    value,
    preKey = ''
) {
    Object.keys(value).forEach(key => {
        if (typeof value[key] == 'string') {
            if (preKey) {
                result.push([
                    `${preKey}.${key}`,
                    value[key],
                    '',
                    '',
                    '',
                ])
            } else {
                result.push([
                    `${key}`,
                    value[key],
                    '',
                    '',
                    ''
                ])
            }
        } else {
            getKeyValue(value[key], preKey ? `${preKey}.${key}` : key)
        }
    })
}

/**
 * 将国际化文件写入xls文件
 * @param {string} fromFileName 
 * @param {string?} toFileName 
 */
exports.readFromJsAndWriteToXls = function (fromFileName = 'i18n.js', toFileName = 'i18n.xls') {
    if (!fromFileName.endsWith('.js')) {
        fromFileName = `${fromFileName}.js`
    }
    if (!toFileName.endsWith('.xls')) {
        toFileName = `${toFileName}.xls`
    }
    const dataPath = resolve(__dirname, '../asset/i18n', fromFileName);
    const data = require(dataPath)
    getKeyValue(data);
    let time = new Date();
    const sheetName = `${time.getFullYear()}-${time.getMonth() + 1}-${time.getDate()}i18n待翻译文件`
    var buffer = build([{ name: sheetName, data: result }]);
    const writePath = resolve(__dirname, '../asset/xls', toFileName)
    fs.writeFileSync(writePath, buffer)
}

